<template>
    <div class="_toast-item" ref="el" :class="msgObj.type.toLowerCase() + ' ' + (contentActive ? 'active' : '')">
        <i class="iconfont" v-html="msgObj.type == 'SUCCESS' ? '&#xe60d;' : '&#xe623;'"></i>
        <div>{{ msgObj.content }}</div>
    </div>
</template>

<script>
import { onMounted, onBeforeUnmount, toRefs, ref } from 'vue'
export default {
    props: {
        msgObj: {
            type: Object,
            default: () => {
                return {
                    id: '1',
                    type: 'INFO',
                    content: '弹出消息',
                    delay: 3000
                }
            }
        }
    },
    setup(props, { emit }) {
        const { msgObj } = toRefs(props)
        let timer = null
        const contentActive = ref(null)
        const el = ref(null)

        const doShow = () => {
            el.value.style.display = 'flex'
            setTimeout(() => {
                contentActive.value = true
            }, 200)
        }

        const doHide = () => {
            contentActive.value = false
            setTimeout(() => {
                el.value.style.display = ''
                emit('close', msgObj.value.id)
            }, 300)
        }

        onMounted(() => {
            doShow()
            timer = setTimeout(() => {
                doHide()
            }, msgObj.value.delay)
        })

        onBeforeUnmount(() => {
            if (timer) {
                clearTimeout(timer)
            }
        })

        return {
            contentActive,
            el
        }
    }
}
</script>
